/**
 * @name: EchartsResizeAndDestoryHooks
 * @author: win10
 * @date: 2024/3/14 17:48
 * @description：EchartsResizeAndDestoryHooks
 * @update: 2024/3/14 17:48
 */
import { onBeforeUnmount, onMounted } from "vue";

/**
 *
 * @param {Ref} chartInstance - ECharts实例的Vue响应式引用
 * @param {Ref} echartsContainerRef - ECharts容器的Vue响应式引用
 * @returns {Object} - 包含销毁ECharts实例的方法
 */
export function useEchartsResizeAndDestory(chartInstance, echartsContainerRef) {
  /**
   * 挂载时监听容器大小变化
   */
  onMounted(() => {
    listenChartsResize();
  });
  /**
   * 卸载时销毁ECharts实例并停止监听容器变化
   */
  onBeforeUnmount(() => {
    destoryEcharts();
    destoryListenChartsResize();
  });

  /**
   * 创建实例用于监听容器大小变化
   */
  const observer = new ResizeObserver(() => {
    chartContainerResize();
  });

  /**
   * 调整图表容器
   * @returns
   */
  function chartContainerResize() {
    const echartsContainer = echartsContainerRef.value;
    if (!echartsContainer) return;

    if (chartInstance.value) {
      chartInstance.value.resize();
    }
  }

  /**
   * 开始监听图表容器大小变化
   * @returns
   */
  function listenChartsResize() {
    const echartsContainer = echartsContainerRef.value;
    if (!echartsContainer) return;

    observer.observe(echartsContainer);
  }
  /**
   * 停止监听图表容器大小变化
   */
  function destoryListenChartsResize() {
    observer.disconnect();
  }
  /**
   * 销毁ECharts实例
   */
  function destoryEcharts() {
    if (chartInstance.value) {
      chartInstance.value.dispose();
      chartInstance.value = undefined;
    }
  }

  return { destoryEcharts };
}

// 在Vue组件中的示例用法
// const { destoryEcharts } = useEchartsResizeAndDestory(registerThemeMethod, chartInstance, echartsContainerRef);
